package com.sunlee.admin.api.module.job.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sunlee.admin.api.module.job.dto.ProductCategoryMappingTaskDTO;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.service.entity.ThirdProductEntity;
import com.sunlee.common.service.service.CategoryService;
import com.sunlee.common.service.service.ProductCategoryMappingService;
import com.sunlee.common.service.service.ProductService;
import com.sunlee.common.service.service.ThirdProductService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 己方商品关联己方分类
 *
 * @author sunlee
 */
@Component("productCategoryMappingTask")
public class ProductCategoryMappingTask implements ITask {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 防止重复执行
     */
    private static boolean isRun = false;

    @Autowired
    private ProductCategoryMappingService productCategoryMappingService;

    @Autowired
    private ThirdProductService thirdProductService;

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public void run(String params) {
        logger.info("productCategoryMappingTask定时任务正在执行，参数为：{}", params);

        if (isRun) {
            throw new BusinessException("不可重复执行");
        }

        isRun = true;

        try {
            start(validaDTO(params));
        } finally {
            isRun = false;
            logger.info("productCategoryMappingTask定时任务执行结束");
        }

    }

    private void start(ProductCategoryMappingTaskDTO dto) {

        // 指定商品更新映射
        List<Long> productIds = dto.getProductIds();

        // 指定商品数量更新
        if (CollectionUtils.isEmpty(productIds)) {

            List<ThirdProductEntity> allThirdProductList = thirdProductService.list(new LambdaQueryWrapper<ThirdProductEntity>()
                    .select(ThirdProductEntity::getResId)
                    .eq(ThirdProductEntity::getSource, dto.getSource())
                    .isNotNull(ThirdProductEntity::getResId)
                    .last(Objects.nonNull(dto.getTotal()), "LIMIT " + dto.getTotal()));

            // 收集商品Id
            productIds = allThirdProductList.stream().map(ThirdProductEntity::getResId).collect(Collectors.toList());
        }

        // 批量处理
        autoMappingByPidList(productIds);
    }

    private void autoMappingByPidList(List<Long> pIds) {
        pIds.forEach(pid -> productCategoryMappingService.autoMappingProductCategoryByProductId(pid));
    }

    private ProductCategoryMappingTaskDTO validaDTO(String params) {
        ProductCategoryMappingTaskDTO dto = validaParseParam(params, ProductCategoryMappingTaskDTO.class);

        if (Objects.isNull(dto.getSource())) {
            throw new BusinessException(ErrorCodeEnum.PARAM_NOT_COMPLETE);
        }

        return dto;
    }
}
